package com.guigu.qingcheng.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.guigu.qingcheng.service.CategoryService;
import com.guigu.qingcheng.service.LocalService;
import com.qingcheng.entity.Result;
import com.qingcheng.pojo.goods.*;
import com.qingcheng.domain.Goods;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import com.qingcheng.pojo.goods.Sku;
import com.qingcheng.pojo.goods.Spu;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.thymeleaf.TemplateEngine;
import org.thymeleaf.context.Context;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.util.HashMap;
import java.util.Map;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URL;
import java.util.*;


@Controller
@RequestMapping("/item")
public class ItemController {

    @Autowired
    private CategoryService categoryService;

    @Autowired
    private TemplateEngine templateEngine;


    @Value("${pathPage}")
    private String pathPage;

    // 创建与商品对应的静态html
    @GetMapping("/createPage")
    public void createPage(String Spu_id, HttpServletRequest request,HttpServletResponse response) throws IOException, ServletException {

        Goods goods=categoryService.findGoodById(Spu_id);
        TbSpu spu=goods.getSpu();
        List list=new ArrayList();
        if(goods.getSkuList()==null || goods.getSpu()==null){
            throw new RuntimeException("该商品以下架或者不存在");
        }
        // 跳转的页面
        String htmlid=goods.getSkuList().get(0).getId();

        // 商品显示添加图片
        if (!StringUtils.isEmpty(spu.getImages())) {
            String[] split1 = spu.getImages().split(",");
            for (int i = 0; i < split1.length; i++) {
                if (split1[i] != "") {
                    list.add(split1[i]);
                }
            }
        }

        for(TbSku s:goods.getSkuList()){
            if (!StringUtils.isEmpty(s.getImages())) {
                String[] split = s.getImages().split(",");
                for (int i = 0; i < split.length; i++) {
                    if (split[i] != "") {
                        list.add(split[i]);
                    }
                }
            }
        }

        // 创建一个Map容器
        Map<String,Object> map=new HashMap<>();

        // 查询商品的一二三级分类
        List category=new ArrayList();
        Map cate=new HashMap();

        TbCategory byId1 = categoryService.findById(spu.getCategory1Id());
        TbCategory byId2 = categoryService.findById(spu.getCategory2Id());
        TbCategory byId3 = categoryService.findById(spu.getCategory3Id());

        if(byId1!=null && byId2!=null && byId3!=null){
            category.add(categoryService.findById(spu.getCategory1Id()));
            category.add(categoryService.findById(spu.getCategory2Id()));
            category.add(categoryService.findById(spu.getCategory3Id()));
            cate.put("cate",category);
            map.put("category",category);
        }else{
            throw new RuntimeException();
        }
        // 添加商品旁的推荐商品
        List<Map> random=categoryService.recommend(spu.getCategory3Id());
        map.put("recommend",random);

        // 添加商品旁的推荐商品列表
        List<TbCategory> recommend=categoryService.recommendlists(spu.getCategory1Id().toString());
        map.put("recommendlists",recommend);

        //sku地址列表
        Map<String,String> urlMap=new HashMap<>();

        for(TbSku sku:goods.getSkuList()){
            if("1".equals(sku.getStatus())){
                String specJson = JSON.toJSONString( JSON.parseObject(sku.getSpec()), SerializerFeature.MapSortField);
                urlMap.put(specJson,sku.getId()+".html");
            }
        }

        // 循环查找sku的个数
        for(TbSku sku:goods.getSkuList()){

            // 上下文
            Context context=new Context();
            map.put("spu",spu);
            map.put("sku",sku);
            map.put("image",list);

            // 商品规格
            if (!StringUtils.isEmpty(spu.getParaItems())) {
                Map ParaItems= JSON.parseObject(spu.getParaItems());
                map.put("ParaItems",ParaItems);
            }
            // 商品参数
            Map SpecItems =JSON.parseObject(sku.getSpec());
            map.put("SpecItems",SpecItems);

            //  查询选择的商品样式
            Map<String,List> SpuSpecItems= (Map<String, List>) JSON.parse(spu.getSpecItems());
            for (String s:SpuSpecItems.keySet()) {
                List<String> list1=SpuSpecItems.get(s);
                List<Map> mapList=new ArrayList<Map>();
                for (String value:list1) {
                    Map map1=new HashMap();
                    map1.put("option",value);
                    Object o = SpecItems.get(s);
                    if(o!=null){
                        if(SpecItems.get(s).equals(value)){
                            map1.put("checked",true);
                        }else {
                            map1.put("checked",false);
                        }
                    }
                    Map<String,String>  spec= (Map)JSON.parseObject(sku.getSpec()) ;//当前的Sku
                    spec.put(s,value);
                    String specJson = JSON.toJSONString(spec , SerializerFeature.MapSortField);
                    map1.put("url",urlMap.get(specJson));
                    mapList.add(map1);
                }
                SpuSpecItems.put(s,mapList);
            }
            map.put("SpuItems",SpuSpecItems);

            //
            context.setVariables(map);
            // 准备文件
            File file=new File(pathPage);
            if(!file.exists()){
                file.mkdirs();
            }
            String id=UUID.randomUUID().toString().substring(0,5);
            File dest=new File(file,sku.getId()+".html");
        try {
            PrintWriter writer=new PrintWriter(dest,"UTF-8");
            templateEngine.process("item",context,writer);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
    }
        request.getRequestDispatcher("/particulars/"+htmlid+".html").forward(request,response);
    }

    @GetMapping("/htmlskip")
    public void htmlskip(String skuid, HttpServletRequest request,HttpServletResponse response) throws ServletException, IOException {
        request.getRequestDispatcher("/particulars/"+skuid).forward(request,response);
    }
}
